package top.kaoshanji.ch04;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * 代码清单 ch04-05：URLConnection示例(4.3.2节、读取数据)
 * author kaoshanji
 * ^_^
 * create time 2024/12/8 9:56
 */
public class URLConnectionTest {

    private static final Logger logger = LogManager.getLogger(URLConnectionTest.class);

    static final String URL_HOST = "http://horstmann.com";

    public static void main(String[] args) {
        logger.info("...代码清单 ch04-05：URLConnection示例(4.3.2节、读取数据)...");

        try {
            var url = new URL(URL_HOST);
            URLConnection connection = url.openConnection();

            // 建立连接
            connection.connect();

            // 打印请求头字段
            Map<String, List<String>> headers = connection.getHeaderFields();
            for (Map.Entry<String, List<String>> entry: headers.entrySet()) {
                String key = entry.getKey();
                for (String value: entry.getValue()) {
                    System.out.println(key + ": " + value);
                }
            }

            // 打印转换函数
            System.out.println("----------");
            System.out.println("getContentType: " + connection.getContentType());
            System.out.println("getContentLength: " + connection.getContentLength());
            System.out.println("getContentEncoding: " + connection.getContentEncoding());
            System.out.println("getDate: " + connection.getDate());
            System.out.println("getExpiration: " + connection.getExpiration());
            System.out.println("getLastModifed: " + connection.getLastModified());
            System.out.println("----------");

            String encoding = connection.getContentEncoding();
            if (encoding == null) {
                encoding = "UTF-8";
            }

            try (var in = new Scanner(connection.getInputStream(), encoding)){
                // 打印内容的第一行
                for (int n = 1; in.hasNextLine() && n <= 10; n++) {
                    System.out.println(in.nextLine());
                }

                if (in.hasNextLine()) {
                    System.out.println(".....");
                }
            }

        }  catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

}
